from typing import List, Union

from fastapi import APIRouter, Depends

from odoo.api import Environment
from odoo.addons.fastapi.dependencies import odoo_env

from odoo.addons.fastapi_odoo_bridge.core.exception import BusinessException, CustomResponse
from odoo.addons.fastapi_odoo_bridge.core.response import custom_response
from ..basemodels.fir_level import Language, TranslationProgram, TranslationClient

router = APIRouter(prefix='/common', tags=['通用接口'])


@router.get(path='/test', summary='测试接口', description='测试接口Hello: World', response_model=CustomResponse[dict])
@custom_response
async def test() -> dict:
    return {"Hello": "World"}


@router.get("/test_exception", summary='测试异常', description='测试异常Exception')
@custom_response
async def test_exception() -> CustomResponse:
    # raise BusinessException('OT0001')
    # raise HTTPException(status_code=400, detail="Test exception")
    raise Exception('OT0001')


@router.get('/get_language',
            response_model=Union[List[Language], dict],
            summary='获取可用的语种',
            description='获取可用的语种')
@custom_response
async def get_available_language(env: Environment = Depends(odoo_env)):
    available_lang_rcds = env['res.lang'].search([])
    languages = [Language(__from_odoo=rcd, __env=env) for rcd in available_lang_rcds]
    return languages


@router.get('/get_program',
            response_model=Union[List[TranslationProgram], dict],
            summary='获取可用的项目',
            description='获取可用的项目')
@custom_response
async def get_available_program(env: Environment = Depends(odoo_env)):
    available_program_data = env['rp.translation.program'].search([])
    programs = [TranslationProgram(__from_odoo=program, __env=env) for program in available_program_data]
    return programs


@router.get('/get_client',
            response_model=Union[List[TranslationClient], dict],
            summary='获取可用的终端',
            description='获取可用的终端')
@custom_response
async def get_available_client(env: Environment = Depends(odoo_env)):
    available_client_data = env['rp.translation.client'].search([])
    clients = [TranslationClient(__from_odoo=client, __env=env) for client in available_client_data]
    return clients


def get_program_and_client(env, program, client):
    """
    获取有可用项目或终端
    """
    program = env['rp.translation.program'].search([('id', '=', program.id)])
    if not program:
        raise BusinessException(code='ORM0002')
    client = env['rp.translation.client'].search([('id', '=', client.id)])
    if not client:
        raise BusinessException(code='ORM0003')
    return program, client
